import { apiAuditUploadImage } from '../../../other/api'
const { regeneratorRuntime } = global;

Page(global.connect(
  state => ({
    ...state.globalReducer,
    ...state.activityReducer,
  }),
  dispatch => ({
    handleLicon1Tap() {
      wx.navigateBack()
    },
    async initPageImageSelect(data) {
      return await dispatch(global.globalReducer.initPageImageSelect(data))
    },
    async customAdsPositionSubmit(data) {
      return await dispatch(global.activityReducer.customAdsPositionSubmit(data))
    },
    async initCustomAdsPositionData(data) {
      return await dispatch(global.activityReducer.initCustomAdsPositionData(data))
    },
    async getUploadToken(data) {
      console.log('handleSubmit')
      const actionRes = await dispatch(global.globalReducer.getUploadToken(data))
      console.log(actionRes)
      if (actionRes.actionStatus !== 'SUCCESS') {
        this.selectComponent('#toast').handleShow({
          message: actionRes.apiMes
        })
      }
    },
  })
)({
  data: {
    tplCount: 1,
    tplAdsType: 2,

    tplPositionName: '',
    tplImageId: '',
    tplImageName: '',
    tplImageUrl: '',
    tplMaterialId: '',
    tplMaterialName: '',
    tplRemark: '',

    tplWidth: '',
    tplHeight: '',
    tplIsAir: 0,
    showTextarea: true,

    uiTempfile: null
  },
  onLoad(e) {
    console.log('onUnload', e)
    // this.handleShowMaterialDialg()
    const {
      index,
      ads_type,
      remark,
      ads_name,
      height,
      width,
      materiel_id,
      materiel_name,
      image_name,
      image_id,
      image_url,
      is_upper_air,
      num,
    } = this.data.customAdsPositionData
    this.setData({
      tplIndex: index || 0,
      tplAdsType: ads_type || 2,
      tplRemark: remark || '',
      tplPositionName: ads_name || '',
      tplHeight: height || '',
      tplWidth: width || '',
      tplMaterialId: materiel_id || '',
      tplMaterialName: materiel_name || '',
      tplImageId: image_id || '',
      tplImageName: image_name || '',
      tplImageUrl: image_url || '',
      tplIsAir: is_upper_air || '',
      tplCount: num || 1,
    })
  },
  onUnload() {
    this.initCustomAdsPositionData({})
  },
  onShow(e) {
    console.log('onShow', e)
    const { imageData } = this.data
    const checkedItem = imageData.find(i => i.checked)
    console.log('checkedItem', checkedItem)
    if (checkedItem) {
      this.setData({
        tplImageId: checkedItem.id,
        tplImageName: checkedItem.image_name,
        tplImageUrl: checkedItem.image_url,
      })
    }
    this.initPageImageSelect({
      multiple: false,
      imageData: []
    })
  },
  handleDelete(e) {
    this.setData({ uiTempfile: null });
  },
  handleChooseImage(e) {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success(res) {
        const { tempFilePaths, tempFiles } = res
        that.setData({
          uiTempfile: { tempFilePaths, tempFiles }
        })
      },
      fail(res) {
        console.error(res)
      }
    })
  },
  handleMovCount(e) {
    let { tplCount } = this.data
    tplCount = Number(tplCount)
    tplCount -= 1
    if (tplCount > 0) {
      this.setData({ tplCount })
    }
  },
  handleAddCount(e) {
    let { tplCount } = this.data
    tplCount = Number(tplCount)
    tplCount += 1
    this.setData({ tplCount })
  },
  handleInput(e) {
    console.log('handleInput', e)
    const obj = {}
    obj[e.currentTarget.dataset.key] = e.detail.value
    this.setData(obj)
  },

  handleHideEvent(e) {
    this.setData({ showTextarea: true })
  },
  handleShowMaterialDialg(e) {
    console.log('handleShowMaterialDialg', e)
    this.setData({ showTextarea: false })

    const { materialList, tplMaterialId } = this.data
    const copy = JSON.parse(JSON.stringify(materialList.data))
    copy.map(i => {
      i.checked = false
      i.show = true
    })
    const checkedItem = copy.find(i => i.id === tplMaterialId)
    console.log('checkedItem', checkedItem, copy)
    if (checkedItem) {
      checkedItem.checked = true
    }
    this.selectComponent('#material').handleShow(null, copy)
  },
  handleMaterial(e) {
    console.log('handleMaterial', e)
    const { cb, data } = e.detail
    const one = data.find(i => i.checked)
    const tplMaterialId = one.id
    const tplMaterialName = one.name
    this.setData({ tplMaterialId, tplMaterialName })
    cb && cb()
  },
  handleEffectImage(e) {
    console.log('handleEffectImage', e)
    const copy = JSON.parse(JSON.stringify(this.data.activityImageList.data))
    copy.map(i => i.selected = false)
    if (this.tplImageId) {
      const one = copy.find(i => i.id === tplImageId)
      if (one) {
        one.selected = true
      }
    }
    this.initPageImageSelect({
      imageData: copy
    })
    global.handleRoute({ route: 'image-select' })
  },
  handleSwitch(e) {
    console.log('handleSwitch', e)
    const checked = e.detail
    this.setData({
      tplIsAir: Number(checked)
    })
  },
  async handleNextStep(e) {
    console.log('handleNextStep', e)
    const {
      tplIndex,
      tplCount,
      tplAdsType,

      tplPositionName,
      tplImageId,
      tplImageName,
      tplImageUrl,
      tplMaterialId,
      tplMaterialName,
      tplRemark,

      tplWidth,
      tplHeight,
      tplIsAir,
      uiTempfile
    } = this.data

    if (!tplPositionName || !tplImageId || !tplMaterialId || !tplWidth || !tplHeight) {
      this.selectComponent('#toast').handleShow({
        message: '请补充广告位信息'
      })
      return
    }

    // todo 上传自定义图
    if(!uiTempfile) {
      this.selectComponent('#toast').handleShow({
        message: '请补充广告位信息'
      })
      return
    }
    await this.getUploadToken({ num: 1 })
    const { token, domain, upDomain } = this.data.uploadTokenRes.data
    const task = []
    let allStores = []

    task.push(
      new Promise((resolve, reject) => {
        const form = {
          url: upDomain,
          filePath: uiTempfile.tempFilePaths[0],
          name: 'file',
          formData: {
            key: Array.isArray(token) ? token[index].key : token.key,
            token: Array.isArray(token) ? token[index].token : token.token
          }
        }
        console.log(form)
        // step1 把图片传到七牛
        wx.uploadFile({
          ...form,
          success(res) {
            resolve(res)
          },
          fail(res) {
            reject(res)
          }
        })
      })
    )
    const upLoadRes = await Promise.all(task);
    console.log(upLoadRes);
    const filepath = JSON.parse(upLoadRes[0].data).key;

    console.log(filepath)

    this.customAdsPositionSubmit({
      filepath,
      index: tplIndex || this.data.storePosition.data.length,
      ads_type: tplAdsType,
      remark: tplRemark,
      ads_name: tplPositionName,
      height: tplHeight,
      width: tplWidth,
      materiel_id: tplMaterialId,
      materiel_name: tplMaterialName,
      image_id: tplImageId,
      image_name: tplImageName,
      image_url: tplImageUrl,
      is_upper_air: tplIsAir,
      num: tplCount,
      selected: true
    });
    wx.navigateBack();
  }
}));